package com.chengv.redismq.config;

import com.chengv.redismq.core.RedisMQDelayMessageScheduledTaskRegistrar;
import com.chengv.redismq.core.RedisMQMessageListenerAnnotationPostProcessor;
import com.chengv.redismq.core.RedisMQStreamListenerRegistrar;
import com.chengv.redismq.core.RedisMQTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * RedisMQ 配置
 *
 * @author chengv
 */
@AutoConfiguration
@Slf4j
public class RedisMQAutoConfiguration {

    @Bean
    public RedisMQTemplate redisMQTemplate(RedisTemplate<String, String> stringRedisTemplate,
                                           RedisTemplate<String, Object> objectRedisTemplate) {
        //noinspection unchecked
        return new RedisMQTemplate(stringRedisTemplate,
                (RedisSerializer<Object>) objectRedisTemplate.getHashValueSerializer());
    }

    @Bean
    public RedisMQStreamListenerRegistrar redisMQStreamListenerRegistrar(RedisMQTemplate redisMQTemplate,
                                                                         ConfigurableEnvironment environment) {
        RedisTemplate<String, String> redisTemplate = redisMQTemplate.getRedisTemplate();
        RedisSerializer<Object> hashValueSerializer = redisMQTemplate.getHashValueSerializer();
        return new RedisMQStreamListenerRegistrar(redisTemplate, hashValueSerializer, environment);
    }

    @Bean
    public RedisMQDelayMessageScheduledTaskRegistrar redisMQDelayMessageScheduledTaskRegistrar(RedisMQTemplate redisMQTemplate) {
        RedisTemplate<String, String> redisTemplate = redisMQTemplate.getRedisTemplate();
        return new RedisMQDelayMessageScheduledTaskRegistrar(redisTemplate);
    }

    @Bean
    public RedisMQMessageListenerAnnotationPostProcessor redisMQMessageListenerAnnotationPostProcessor() {
        return new RedisMQMessageListenerAnnotationPostProcessor();
    }
}
